<?php

class Language {
    private $language;
    private $translations;
    
    public function __construct($language = 'ja') {
        // Set default language to Japanese
        $this->language = $language;
        
        // Check if language is set in session or GET parameter
        if (isset($_GET['lang'])) {
            $this->language = $_GET['lang'];
        } elseif (isset($_SESSION['language'])) {
            $this->language = $_SESSION['language'];
        }
        
        // Validate language
        if (!in_array($this->language, ['zh', 'ja', 'en'])) {
            $this->language = 'ja'; // Default to Japanese
        }
        
        // Save language to session
        $_SESSION['language'] = $this->language;
        
        // Load translations
        $this->loadTranslations();
    }
    
    private function loadTranslations() {
        $langFile = __DIR__ . '/lang/' . $this->language . '.php';
        if (file_exists($langFile)) {
            $this->translations = include $langFile;
        } else {
            // Fallback to Japanese if language file not found
            $this->translations = include __DIR__ . '/lang/ja.php';
        }
    }
    
    public function get($key) {
        return isset($this->translations[$key]) ? $this->translations[$key] : $key;
    }
    
    public function getCurrentLanguage() {
        return $this->language;
    }
    
    public function getLanguageOptions() {
        return [
            'zh' => $this->get('language_zh'),
            'ja' => $this->get('language_ja'),
            'en' => $this->get('language_en')
        ];
    }
}